#pragma once

#include <iostream>
#include <string>
#include <cerrno>
#include <cstring>

#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>
#include "log.hpp"

#define SIZE 1024

class UDP
{
public:
    UDP(uint16_t port, std::string ip = "0.0.0.0")
        :_port(port)
        ,_ip(ip)
        ,_sock(-1)
    {}

    void InitUdp()
    {
        // 1.定义网络套接字
        _sock = socket(AF_INET, SOCK_DGRAM, 0); // 定义网络套接字,数据报的形式
        if (_sock < 0)
        {
            logMessage(FATAL, "%d: %s", errno, strerror(errno));
            exit(2);
        }
        logMessage(NORMAL, "create sock success!");

        // 2.bind
        // 2.0 定义套接字结构体,把套接字的形式,ip,端口号给进去
        struct sockaddr_in local;
        bzero(&local, sizeof local);
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);  // 从主机到网络,使用htons/htonl接口
        local.sin_addr.s_addr = inet_addr(_ip.c_str());  // 把字符串转成点分十进制

        if (bind(_sock, (struct sockaddr*)&local, sizeof(local)) < 0)
        {
            logMessage(FATAL, "%d: %s", errno, strerror(errno));
            exit(3);
        }

        logMessage(NORMAL, "bind success!");
    }

    void start()
    {
        char buffer[SIZE]; // 来读取套接字

        // 服务器是永不退出的
        while (true)
        {
            memset(buffer, 0, sizeof buffer);
            // 先定义套接字结构体,从网络中读取数据
            struct sockaddr_in peer;
            bzero(&peer, sizeof peer);
            socklen_t len = sizeof peer;
            ssize_t s = recvfrom(_sock, buffer, sizeof buffer, 0, (struct sockaddr*)&peer, &len);
            if (s > 0)
            {
                buffer[s] = 0;
                std::string message_ip = inet_ntoa(peer.sin_addr); // 从网络到主机,从点分十进制到字符串使用inet_ntoa接口
                uint16_t message_port = ntohs(peer.sin_port); // 从网络到主机

                std::cout << message_ip << " " << message_port << "# " << buffer << std::endl;

                // 原封不动的回复
                std::string copy;
                copy += message_ip;
                copy += " ";
                copy += std::to_string(message_port);
                copy += "# ";
                copy += buffer;
                sendto(_sock, copy.c_str(), copy.size(), 0, (struct sockaddr*)&peer, sizeof(peer));
            }
        }
    }

    ~UDP()
    {
        if (_sock >= 0) close(_sock);
    }
private:
    std::string _ip;  // ip地址
    uint16_t _port;   // 端口号
    int _sock;      // 套接字  初始化给-1
};
